import React from 'react';
import { ActivityIndicator, StatusBar, StyleSheet, View, Platform } from 'react-native';
import { observer, inject } from 'mobx-react';
import PropTypes from 'prop-types';
import { UpdateApi } from '../api';
import VersionStoreObj from '../store/VersionStore';
import GlobalStyles from '../style/GlobalStyles';
import NavigationUtil from '../navigation/NavigationUtil';

@inject(['VersionStore'])
@observer
export default class VersionLoadingScreen extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            // 每次更新逻辑版本需要+1
            version: '1'
        };
        NavigationUtil.navigation = this.props.navigation;
        this._bootstrapAsync();
    }

    static propTypes = {
        VersionStore: PropTypes.objectOf(VersionStoreObj).isRequired
    };

    _bootstrapAsync = async () => {
        const { version } = this.state;
        const { VersionStore } = this.props;
        const clientType = Platform.OS === 'android' ? 1 : 0;
        const { code, data } = await UpdateApi.getVersion({ logicVersion: version, clientType });
        const isUpdate = !!(code && code.code === 2000 && data.version.logicVersion > version);
        if (isUpdate) {
            VersionStore.setMessage(data.messages);
            VersionStore.setVersion(data.version);
            this.isCancelVersion();
        } else {
            NavigationUtil.goPage('Index');
        }
    };

    // 当前版本是否取消更新
    isCancelVersion() {
        global.storage.load({ key: 'cancelVersion' }).then(ret => {
            if (ret.cancelVersion === version && ret.isCancel === 1) {
                NavigationUtil.goPage('Index');
            } else {
                this.isLateVersion();
            }
        }).catch(() => {
            this.isLateVersion();
        });
    }

    // 当前版本是否稍候更新
    isLateVersion() {
        global.storage.load({ key: 'lateVersion' }).then(ret => {
            // 更新时间间隔为 6 小时
            if (ret.lateVersion === version && ret.lateTime + 1000 * 3600 * 6 >= Date.now()) {
                NavigationUtil.goPage('Index');
            } else {
                NavigationUtil.goPage('Update');
            }
        }).catch(() => {
            NavigationUtil.goPage('Update');
        });
    }

    render() {
        return (
            <View style={styles.container}>
                <ActivityIndicator/>
                <StatusBar barStyle="default"/>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        width: GlobalStyles.DEVICE_WIDTH,
        height: GlobalStyles.DEVICE_HEIGHT
    }
});
